package com.example.myapplication1.publishFriendCircle;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.example.myapplication1.R;

/**
 * Copyright (C), 2020, 重庆八进制有限公司
 *
 * @author: SuperChen
 * @last-modifier: SuperChen
 * @version: 1.0
 * @create-date: 2020/9/2 11:03
 * @last-modify-date: 2020/9/2 11:03
 * @description:
 */
public class PublishHubActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private AddPictureRecyclerView<Uri, Holder> rv;
    private Adapter adapter;

    private View llBottomParent;
    private ImageView ivBottmTrash;
    private TextView tvBottomTrash;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_hub);
        toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("发布");
        toolbar.setTitleTextColor(0xffffffff);
        toolbar.setBackgroundColor(0xff1B88EE);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        llBottomParent = findViewById(R.id.constraintBottomParent);
        ivBottmTrash = findViewById(R.id.ivBottmTrash);
        tvBottomTrash = findViewById(R.id.tvBottomTrash);
        initRv();
    }

    private void initRv() {
        rv = findViewById(R.id.rv);
        rv.bringToFront();
        rv.setLayoutManager(new GridLayoutManager(this, 3));
        rv.setDragListener(new BottomDeleteDragListener<Uri, Holder>() {
            @Override
            public boolean stateIsInSpecialArea(boolean isInArea, boolean isFingerUp, int position) {
                ivBottmTrash.setSelected(isInArea);
                llBottomParent.setSelected(isInArea);
                if (isInArea) {
                    tvBottomTrash.setText("松手即可删除");
                    //当图片被清空时，则重新赋值，避免拍摄视频需要退出后重新进入
                    if (isFingerUp) {
                        if (adapter != null) {
                            adapter.removeItem(position);
                            adapter.notifyItemRangeRemoved(position, adapter.getItemCount());
                        }
                    }
                } else {
                    tvBottomTrash.setText("拖动到此处删除");
                }
                return false;
            }

            @Override
            public boolean canDrag(Holder viewHolder, int position, @Nullable Uri o) {
                return viewHolder.getItemViewType() != AddPictureTouchAdapter.VIEW_TYPE_ADD_ITEM;
            }

            @Override
            public void onPreDrag() {
                doTransAniAfterGone(llBottomParent, true);
            }

            @Override
            public void onDraging() {
            }

            @Override
            public void onReleasedDrag() {
                doTransAniAfterGone(llBottomParent, false);
            }
        });
        adapter = new Adapter(this);
        adapter.setOnItemClickListener(new AddPictureTouchAdapter.AddPictureOnItemClickListener<Uri>() {
            @Override
            public void onItemClick(@Nullable Uri data, boolean isAddPictureItem) {
                if (isAddPictureItem) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (ActivityCompat.checkSelfPermission(PublishHubActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                            goGallery();
                        } else {
                            ActivityCompat.requestPermissions(PublishHubActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                        }
                    } else {
                        goGallery();
                    }
                }
            }
        });
        rv.setAdapter(adapter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                goGallery();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 2) {
                Uri uri = data.getData();
                if (uri != null) {
                    String path = GalleryUtil.getRealPathFromUri(PublishHubActivity.this, uri);
                    if (adapter != null) {
                        adapter.addItem(uri);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    /**
     * 图库
     */
    private void goGallery() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (adapter != null) {
            adapter.destroy();
            adapter = null;
        }
    }

    public class Adapter extends AddPictureTouchAdapter<Uri, Holder> {

        public Adapter(@NonNull Context context) {
            super(context);
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            final Path roundPath = new Path();
            final RectF rectF = new RectF();
            View view;
            if (viewType == VIEW_TYPE_ADD_ITEM) {
                view = new FrameLayout(getContext());
                ImageView iv = new AppCompatImageView(getContext());
                iv.setImageResource(R.mipmap.ic_launcher);
                FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(SizeUtils.dp2px(55), SizeUtils.dp2px(55));
                lp.gravity = Gravity.CENTER;
                ((FrameLayout) view).addView(iv, lp);
                view.setBackgroundResource(R.drawable.ic_launcher_background);
            } else {
//                view = new AppCompatImageView(getContext()) {
//                    @Override
//                    protected void onDraw(Canvas canvas) {
//                        canvas.save();
//                        rectF.set(getLeft(), getTop(), getRight(), getBottom());
//                        roundPath.addRoundRect(rectF, SizeUtils.dp2px(10), SizeUtils.dp2px(10), Path.Direction.CCW);
//                        canvas.clipPath(roundPath);
//                        super.onDraw(canvas);
//                        canvas.restore();
//                    }
//                };
                view = new AppCompatImageView(getContext());
            }
            RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.leftMargin = SizeUtils.dp2px(5);
            lp.topMargin = SizeUtils.dp2px(5);
            lp.rightMargin = SizeUtils.dp2px(5);
            lp.bottomMargin = SizeUtils.dp2px(5);
            view.setMinimumHeight(SizeUtils.dp2px(115));
            view.setLayoutParams(lp);
            return new Holder(view);
        }

        @Override
        protected void onBindViewHolder(@NonNull Holder holder, int position, @Nullable Uri data, boolean isAddPictureItem) {
            if (isAddPictureItem) {
                return;
            }
            final ImageView iv = (ImageView) holder.itemView;
            Glide.with(getContext())
                    .load(data)
                    .into(iv);
        }
    }


    public static class Holder extends RecyclerView.ViewHolder {


        public Holder(@NonNull View itemView) {
            super(itemView);
        }
    }

    public static void doTransAniAfterGone(final View view, final boolean show) {
        if (null == view) return;
        TranslateAnimation t;
        if (show) {
            t = new TranslateAnimation(0, 0, 0, SizeUtils.dp2px(-60));
        } else {
            t = new TranslateAnimation(0, 0, SizeUtils.dp2px(-60), 0);
        }
        t.setFillAfter(true);
        t.setDuration(300);
        t.setRepeatCount(0);
        t.setRepeatMode(Animation.REVERSE);
        t.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                if (show) view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (!show) {
                    view.setVisibility(View.GONE);
                    view.clearAnimation();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        view.startAnimation(t);
    }
}
